#include "FileView.h"


FileView::FileView( QWidget* parent )
	: QTreeWidget( parent )
{
	qDebug() << "Info : start FileViewer...";
	QStringList labels;
	setSelectionMode(QAbstractItemView::ExtendedSelection);
	setColumnCount(3);
    labels << tr("Fichier") << tr("Urgence") << tr("Chemin") << tr("Hash");
	header()->setResizeMode(QHeaderView::ResizeToContents);
    setHeaderLabels(labels);
	Filelevel = 0;
	CheckDoublon = false;
	floodMsgBox = false;
	connect(this, SIGNAL(itemSelectionChanged()), this, SLOT(ItemsSelectedChange()));
	connect(this,SIGNAL(TaskToShowInStatusbar(QString)), this, SLOT(FloodMSg(QString)));
}

FileView::~FileView()
{
	qDebug() << "Info :  stop FileViewer...";
}

void FileView::setFilelevel(int new_val)
{
	if (new_val > 100)
	{
		Filelevel = 100;
	}
	else if (new_val < 0)
	{
		Filelevel = 0;
	}
	else
	{
		Filelevel = new_val;
	}
}

void FileView::Set_Path_Updater(QString NewPath)
{
	Path_Updater = NewPath;
}
void FileView::AddFolder()
{
	bool err = false;
	double countFile = 0;
	QString RelativePath;
	
	QString folderName = QFileDialog::getExistingDirectory(
                         this,
                         trUtf8("Selectionnez les dossiers a ajouter"));
	
	if (folderName.isEmpty())
	{return;}	
	
	QFileInfoList fileslist;
	
	emit TaskToEnableGUI(false);
	
	fileslist = getFiles(QDir(folderName), QStringList(), true);
	
	for (int i = 0; i < fileslist.size(); ++i)
	{
		QList<QTreeWidgetItem *> CheckList;
		if(CheckDoublon)
		{CheckList = this->findItems(fileslist[i].fileName(),Qt::MatchExactly);}
		
		if (CheckList.size() != 0)
		{
			for (int k = 0; k < CheckList.size(); ++k)
			{
				//Check AbsolutePath doublons
				if (QString::compare(CheckList[k]->text(2),fileslist[i].absolutePath()) != 0)
				{
					RelativePath = fileslist[i].absolutePath();
					RelativePath = RelativePath.remove(Path_Updater);
					if(QString::compare(CheckList[k]->text(2),RelativePath) != 0)
					{
						//qDebug() << "RelativePath :" << RelativePath << "Absolut path" << fileslist[i].absolutePath() << "Tree :"<< CheckList[k]->text(2);
						AddQTreeWidgetItem(fileslist[i].fileName(), Filelevel, fileslist[i].absolutePath());
						countFile++;
					}
					else
					{err = true;}	
				}
				else
				{
					err = true;
				}
				QCoreApplication::processEvents();
			}
		}
		else
		{
			AddQTreeWidgetItem(fileslist[i].fileName(), Filelevel, fileslist[i].absolutePath());
			countFile++;
		}
		QCoreApplication::processEvents();
	}
	emit TaskToEnableGUI(true);
	if (countFile != 0)
	{
		if(!err)
		{emit TaskToShowInStatusbar(QString::number(countFile) + trUtf8(" fichiers ajoutés."));}
		else
		{emit TaskToShowInStatusbar(QString::number(countFile) + trUtf8(" fichiers ajoutés (Doublons détectés)."));}
	}
	else
	{emit TaskToShowInStatusbar(trUtf8("Aucuns fichiers ajoutés."));}
}

void FileView::AddFile()
{
	QString RelativePath;
	bool err = false;
	int countFile = 0;
	QStringList fileNames = QFileDialog::getOpenFileNames(
                         this,
                         trUtf8("Selectionnez les fichiers a ajouter"));

	if (fileNames.size() == 0)
	{return;}
	
	emit TaskToEnableGUI(false);
	
	QFileInfo TmpFile;
	for (int i = 0; i < fileNames.size(); ++i)
	{
		//Check if the item exists
		TmpFile.setFile(fileNames.at(i));
		//Check Filename doublons
		QList<QTreeWidgetItem *> CheckList;
		if(CheckDoublon)
		{CheckList = this->findItems(TmpFile.fileName(),Qt::MatchExactly);}
		
		if (CheckList.size() != 0)
		{
			for (int k = 0; k < CheckList.size(); ++k)
			{
				//Check AbsolutePath doublons
				if (QString::compare(CheckList[k]->text(2),TmpFile.absolutePath()) != 0)
				{
					RelativePath = TmpFile.absolutePath();
					RelativePath = RelativePath.remove(Path_Updater);
					if(QString::compare(CheckList[k]->text(2),RelativePath) != 0)
					{
						AddQTreeWidgetItem(TmpFile.fileName(), Filelevel, TmpFile.absolutePath());
						countFile++;
					}
					else
					{err = true;}	
				}
				else
				{
					err = true;
				}
				QCoreApplication::processEvents();
			}
		}
		else
		{
			AddQTreeWidgetItem(TmpFile.fileName(), Filelevel, TmpFile.absolutePath());
			countFile++;
		}
		QCoreApplication::processEvents();
	}
	emit TaskToEnableGUI(true);
	if (countFile != 0)
	{
		if(!err)
		{emit TaskToShowInStatusbar(QString::number(countFile) + trUtf8(" fichiers ajoutés."));}
		else
		{emit TaskToShowInStatusbar(QString::number(countFile) + trUtf8(" fichiers ajoutés (Doublons détectés)."));}
	}
	else
	{emit TaskToShowInStatusbar(trUtf8("Aucuns fichiers ajoutés."));}

}

void FileView::Insert_updater(QString Path, QString FileName, int priority)
{
	QColor backgroundCol;
	QTreeWidgetItem *item;
	
	item = new QTreeWidgetItem(this);
	item->setText(0, FileName);
	
	backgroundCol = Qt::red;
	item->setIcon(0,QIcon(QString::fromUtf8(":/Others/Ressources/refresh.png")));
	emit OneItemWasAdded();
	
	item->setBackground(0,QBrush(backgroundCol));
	item->setText(1,QString::number(priority));
	item->setText(2, Path);
}
void FileView::AddQTreeWidgetItem(QString filename, int level, QString AbsolutePath, QString sha1)
{
	QColor backgroundCol;
	QTreeWidgetItem *item;
	
	item = new QTreeWidgetItem(this);
	item->setText(0, filename);
	
	item->setIcon(0,QIcon(QString::fromUtf8(":/Others/Ressources/refresh.png")));
	
	if(sha1.isEmpty())
	{
		backgroundCol = Qt::green;
		emit OneItemWasAdded();
	}
	else
	{backgroundCol = Qt::white;}
	
	item->setBackground(0,QBrush(backgroundCol));
	item->setText(1,QString::number(level));
	item->setText(2, AbsolutePath);
	item->setText(3, sha1);
}

void FileView::InsertFileFromXML(QString Sha1, QString Path, QString FileName, int priority)
{
	AddQTreeWidgetItem(FileName,priority,Path,Sha1);
}

QFileInfoList FileView::getFiles(QDir fromDir, const QStringList& filters, bool recursive)
{
	QFileInfoList files;
	
	foreach ( QFileInfo file, fromDir.entryInfoList( QDir::AllEntries | QDir::NoDotAndDotDot, QDir::DirsFirst | QDir::Name ) )
	{
		if (file.isFile() && (filters.isEmpty() || QDir::match(filters, file.fileName())))
			files << file;
			
		else if (file.isDir() && recursive)
		{
			fromDir.cd(file.filePath());
			files << getFiles(fromDir, filters, recursive);
			fromDir.cdUp();
		}
	}
	return files;
}
void FileView::DeleteSelectedFile()
{
	QList<QTreeWidgetItem *> Del_List = selectedItems();
	if(Del_List.size()!=0)
	{
		QMessageBox msgBox;
		msgBox.setText("");
		msgBox.setInformativeText(trUtf8("Supprimer ") + QString::number(Del_List.size()) + trUtf8(" fichier(s) de la liste."));
		msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
		msgBox.setDefaultButton(QMessageBox::Cancel);
		msgBox.setIcon(QMessageBox::Question);
		
		if(msgBox.exec() == QMessageBox::Ok)
		{
			for (int i = 0; i < Del_List.size(); ++i)
			{
				delete Del_List[i];
				QCoreApplication::processEvents();
			}
		}
	}
}

void FileView::ItemsSelectedChange()
{
	QList<QTreeWidgetItem *> Edit_List = selectedItems();
	if(Edit_List.size()!=0)
	{emit TaskToShowGbEdit(true);}
	else
	{emit TaskToShowGbEdit(false);}
}
void FileView::SetLevelSelectedFiles(int lvl)
{
	QList<QTreeWidgetItem *> Edit_List = selectedItems();
	for (int i = 0; i < Edit_List.size(); ++i)
	{
		Edit_List[i]->setText(1,QString::number(lvl));
	}	
}
void FileView::setCheckDoublon(bool new_val)
{
	CheckDoublon = new_val;
}
void FileView::setfloodMsgBox(bool new_val)
{
	floodMsgBox = new_val;
}
void FileView::FloodMSg(QString msg)
{
	if(floodMsgBox)
	{
		QMessageBox msgBox;
		msgBox.setText("");
		msgBox.setInformativeText(msg);
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		//msgBox.setIcon(QMessageBox::Question);
		msgBox.exec();
	}
}
QList<UpdateFile*> FileView::getList()
{
	QList<UpdateFile*> ListFiles;
	UpdateFile* tmpFile;
	QList<QTreeWidgetItem*> TmpItems = this->findItems(QString(""),Qt::MatchContains);
	for(int i=0; i<(TmpItems.size());i++)
	{
		tmpFile = new UpdateFile(TmpItems[i]->text(0), TmpItems[i]->text(2), TmpItems[i]->text(1).toInt(), TmpItems[i]->text(3));
		ListFiles.append(tmpFile);		
	}
	return ListFiles;
}
